<template>
    <el-container>
        <el-main>
            <avue-crud ref="multipleTable" :data="tableData" :option="tableColumns" :page="page" @refresh-change="refresh"
                @search-change="searchChange" @search-reset="searchReset" @filter-change="filterChange" @size-change="sizeChange"
                @current-change="currentChange">
                <template slot="menuLeft">
                    <el-button v-for="(item,index) in btnList" :key="index" :type="item.type" :class="item.hide?'hide':''"
                        @click.native="btnclick(item.funName)" size="small">{{ item.label }}</el-button>
                </template>
                <template slot="menu" slot-scope="{row}">
                    <el-button v-if="$store.getters.userInfo.user_type === 0 && row.status === 0 && $store.getters.userInfo.company_id !== row.id"
                        size="small" type="text" class="successbtn-color" @click.native="enabled(row)">
                        启用
                    </el-button>
                    <el-button v-if="$store.getters.userInfo.user_type === 1 || $store.getters.userInfo.user_type === 0"
                        size="small" type="text" class="primarybtn-color" @click.native="edit(row)">
                        编辑
                    </el-button>
                    <el-button v-if="$store.getters.userInfo.user_type === 0 && $store.getters.userInfo.company_id !== row.id"
                        size="small" type="text" class="primarybtn-color" @click.native="companyauth(row)">
                        单位授权
                    </el-button>
                    <el-button v-if="$store.getters.userInfo.user_type === 0 && $store.getters.userInfo.company_id !== row.id"
                        size="small" type="text" class="primarybtn-color" @click.native="dictauth(row)">
                        字典授权
                    </el-button>
                    <el-button v-if="$store.getters.userInfo.user_type === 0 && $store.getters.userInfo.company_id !== row.id"
                        size="small" type="text" class="dangerbtn-color" @click.native="del(row)">
                        删除
                    </el-button>
                    <el-button v-if="$store.getters.userInfo.user_type === 0 && row.status === 1 && $store.getters.userInfo.company_id !== row.id"
                        size="small" type="text" class="dangerbtn-color" @click.native="disabled(row)">
                        禁用
                    </el-button>
                    <!-- <el-button 
            v-if="$store.getters.userInfo.user_type === 1"
            size="small"
            type="text"
            class="primarybtn-color"
            @click.native="userEdit(row)">
            账号修改
          </el-button> -->
                    <el-button v-if="$store.getters.userInfo.user_type === 2" size="small" type="text" class="primarybtn-color"
                        @click.native="lookDetail(row)">
                        查看
                    </el-button>
                </template>
                <template slot="status" slot-scope="scope">
                    <div v-if="scope.row.status === 1" style="color:#13ce66">启用</div>
                    <div v-if="scope.row.status === 0" style="color:#ff4949">禁用</div>
                </template>
            </avue-crud>
            <el-dialog :title="dialogFormTitle" :destroy-on-close="false" :close-on-click-modal="false" :visible.sync="dialogFormVisible"
                :before-close="handleCloseBindDialogForm" width="600px">
                <div style="height:60vh;overflow:auto">
                    <df-element-form v-if="formHackReset" :formConfig="formConfig[0]" :value="formValue" ref="customForm">
                    </df-element-form>
                </div>
                <el-row slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button size="small" type="primary" @click="save">保存</el-button>
                    <el-button size="small" @click="dialogFormVisible = false;">取消</el-button>
                </el-row>
            </el-dialog>
            <el-dialog :title="dialogCompanyAuthTitle" :destroy-on-close="false" :close-on-click-modal="false"
                :visible.sync="dialogCompanyAuthVisible" :before-close="handleCloseBindDialogForm" width="400px">
                <div style="height:60vh;overflow:auto">
                    <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" default-expand-all
                        highlight-current :default-checked-keys="treeCheckedData" :expand-on-click-node="false">
                    </el-tree>
                </div>
                <el-row slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button size="small" type="primary" @click="authSave">授权</el-button>
                    <el-button size="small" @click="dialogCompanyAuthVisible = false;">取消</el-button>
                </el-row>
            </el-dialog>
            
            <el-dialog :title="dialogDictAuthTitle" :destroy-on-close="false" :close-on-click-modal="false"
                :visible.sync="dialogDictAuthVisible" :before-close="handleCloseBindDialogForm" width="400px">
                <div style="height:60vh;overflow:auto">
                    <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" default-expand-all
                        highlight-current :default-checked-keys="treeCheckedData" :expand-on-click-node="false">
                    </el-tree>
                </div>
                <el-row slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button size="small" type="primary" @click="authSave">授权</el-button>
                    <el-button size="small" @click="dialogDictAuthVisible = false;">取消</el-button>
                </el-row>
            </el-dialog>
        </el-main>
    </el-container>
</template>

<script>
    import {
        api
    } from "@/api/common";
    import {
        getFormConfigData
    } from '@/const/views/system/company/company'
    import {
        resolveAllEunuchNodeId
    } from '@/util/util'
    // import { getFilesByKey } from '@/util/upload';
    import SearchCol from '@/components/view/search_col'

    export default {
        components: {
            SearchCol
        },
        data() {
            return {
                formHackReset: true,
                checkAll: false,
                editCompanyID: '',
                editType: '',
                treeData: [], // 菜单树
                treeCheckedData: [],
                formConfig: [], // 表单配置数据
                formValue: {}, // 表单值
                dialogFormVisible: false, // 弹出框显示
                dialogFormTitle: '', // 弹出框标题
                dialogCompanyAuthVisible: false, // 单位授权弹出框
                dialogCompanyAuthTitle: '', // 单位授权弹出标题
                dialogDictAuthVisible: false,
                dialogDictAuthTitle: '',
                page: {
                    // pageSizes: [5, 10, 20, 30, 40],
                    currentPage: 1,
                    total: 0,
                    pageSize: 10
                }, // 分页信息
                searchForm: {}, // 搜索框记录
                // searchList: [{
                //     prop: 'keyword',
                //     label: '快捷搜索',
                //     placeholder: '名称,简称,编码,标识'
                // }],
                filterForm: {}, // 过滤框记录
                btnList: [{
                    type: "primary",
                    funName: "add",
                    label: "添加",
                    hide: this.$store.getters.userInfo.user_type !== 0
                }],
                // menuBtnList: [{ // 表格操作列按钮
                //     type: "primary",
                //     funName: "edit",
                //     label: "编辑",
                //     icon: "el-icon-edit",
                // }, {
                //     type: "primary",
                //     funName: "companyauth",
                //     label: "单位授权",
                //     icon: "el-icon-edit",
                // }, {
                //     type: "danger",
                //     funName: "del",
                //     label: "删除",
                //     icon: "el-icon-del",
                // }],
                tableData: [], // 表格数据
                tableColumns: { // 表格列配置
                    border: true,
                    stripe: false,
                    showHeader: true,
                    index: false,
                    page: true,
                    align: 'left',
                    menuAlign: 'center',
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    menu: true,
                    columnBtn: false,
                    searchMenuSpan: 4,
                    column: [{ // 表格列
                        prop: "name",
                        label: "名称"
                    }, {
                        prop: "short_name",
                        label: "简称",
                    }, {
                        prop: "code",
                        label: "编码"
                    }, {
                        prop: "tag",
                        label: "标识"
                    }, {
                        prop: "status",
                        label: "状态",
                        slot: true
                    }, {
                        prop: "username",
                        label: "管理员账号"
                    }, {
                        prop: "realname",
                        label: "管理员姓名"
                    }, {
                        label: '快捷搜索',
                        prop: 'keyword',
                        search: true,
                        hide: true,
                        searchPlaceholder: '名称,简称,编码,标识'
                    }],
                }
            }
        },
        created() {
            this.getTableList();
            this.getFormConfig();
        },
        methods: {
            // 表格刷新
            refresh() {
                this.getTableList();
            },
            // 搜索
            searchChange(params, done) {
                this.page.currentPage = 1
                this.getTableList(params)
                Object.assign(this.searchForm, params)
                done()
            },
            // 搜索清空
            searchReset() {
                this.page.currentPage = 1
                this.$set(this.searchForm, 'keyword', '')
                this.getTableList()
            },
            // 表格过滤（高级搜索）
            filterChange(result) {
                this.getTableList(result)
                this.filterForm = result
            },
            // 分页
            sizeChange(val) {
                this.page.currentPage = 1
                this.page.pageSize = val
                this.getTableList();
            },
            // 当前页
            currentChange(val) {
                this.page.currentPage = val
                this.getTableList();
            },
            // 绑定弹窗子组件的关闭
            handleCloseBindDialogForm() {
                this.dialogFormVisible = false
                this.dialogFormTitle = ''
                this.dialogCompanyAuthVisible = false
                this.dialogCompanyAuthTitle = ''
                this.dialogDictAuthVisible = false
                this.dialogDictAuthTitle = ''
                this.editCompanyID = ''
                this.treeData = []
                this.editType = ''
            },
            // 树
            getTreeData(id, _url) {
                this.checkAll = false
                let _this = this,
                    params = {
                        companyId: id
                    }
                if (_this.editType === 'DICT') {
                    params['type'] = 'dict';
                }
                _this.axios.post(_url, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.treeData = res.data.data.tree
                        _this.treeCheckedData = res.data.data.checked
                        // if (this.editType != '银行授权') {
                        _this.treeCheckedData = resolveAllEunuchNodeId(_this.treeData, _this.treeCheckedData, [])
                        // }
                        _this.$refs.tree.setCheckedKeys(_this.treeCheckedData);
                    } else {
                        _this.treeData = []
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.treeData = []
                    console.log('调用失败', err)
                })
            },
            handleCheckAllChange() {
                if (this.checkAll) {
                    this.$refs.tree.setCheckedNodes(this.treeData);
                } else {
                    this.$refs.tree.setCheckedKeys([]);
                }
            },
            // 获取表格数据
            getTableList(where) {
                let params = {
                    page: this.page.currentPage,
                    limit: this.page.pageSize
                }
                params = Object.assign({}, params, this.searchForm)
                params = Object.assign({}, params, this.filterForm)
                if (where) {
                    params = Object.assign({}, params, where)
                }
                let _this = this
                _this.axios.post(api.getCompanyList, params).then((res) => {
                    console.log(res)
                    if (res.data.code == 10000) {
                        _this.tableData = res.data.data.list
                        _this.page.total = res.data.data.count
                    } else {
                        _this.tableData = []
                        _this.page.total = 0
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.tableData = []
                    _this.page.total = 0
                    console.log('调用失败', err)
                })
            },
            // 获取表单配置
            getFormConfig() {
                var _this = this

                _this.formConfig = getFormConfigData()
            },
            // 按钮点击（转发）
            btnclick(func) {
                this[func]()
            },
            // 启用
            enabled(row) {
                let url = api.companySts,
                    params = {
                        id: '',
                        status: 1
                    },
                    _this = this
                params.id = row.id

                _this.$confirm('是否确认启用单位?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params)
                })
            },
            // 禁用
            disabled(row) {
                let url = api.companySts,
                    params = {
                        id: '',
                        status: 0
                    },
                    _this = this

                params.id = row.id

                _this.$confirm('是否确认禁用单位?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params)
                })
            },
            // 添加
            add() {
                this.$set(this.formConfig[0], 'disabled', false)
                this.formValue = {}
                this.formHackReset = false
                this.$nextTick(() => {
                    this.formHackReset = true
                })
                this.dialogFormVisible = true
                this.dialogFormTitle = '添加单位'
            },
            // 表格行操作列按钮点击（转发）
            rowbtnclick(func, row) {
                this[func](row)
            },
            // 编辑
            async edit(row) {
                let _this = this
                _this.axios.post(api.getCompanyById, {
                    id: row.id
                }).then((res) => {
                    if (res.data.code == 10000) {
                        _this.$set(_this.formConfig[0], 'disabled', false)
                        _this.formValue = Object.assign({}, res.data.data)
                        _this.formHackReset = false
                        _this.$nextTick(() => {
                            _this.formHackReset = true
                        })
                        _this.dialogFormVisible = true
                        _this.dialogFormTitle = '编辑【' + row.name + '】单位'
                    } else {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        })
                    }
                }).catch((err) => {
                    _this.$message({
                        showClose: false,
                        message: '获取单位详情失败！',
                        type: 'error'
                    })
                    console.log('调用失败', err)
                })
            },
            // 单位授权
            companyauth(row) {
                // console.log(row);
                this.editCompanyID = row.id
                this.editType = 'COM'
                this.dialogCompanyAuthVisible = true
                this.dialogCompanyAuthTitle = row.company_name
                this.getTreeData(row.id, api.getAuthorizeTree)
            },
            // 字典授权
            dictauth(row) {
                this.editCompanyID = row.id
                this.editType = 'DICT'
                this.dialogDictAuthVisible = true
                this.dialogDictAuthTitle = row.company_name
                this.getTreeData(row.id, api.getAuthorizeTree)
            },
            authSave() {
                let _url = '',
                    params = {
                        auths: this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()).join(','),
                        companyId: this.editCompanyID
                    }
                if (this.editType === 'COM') {
                    _url = api.authorizeCompany
                } else if (this.editType === 'DICT') {
                    _url = api.authorizeDict
                }

                this.handleAxiosFun(_url, params)
            },
            // 删除
            del(row) {
                let url = api.companyRmv,
                    _this = this,
                    params = {
                        id: row.id,
                    }

                _this.$confirm('该操作会永久删除该单位, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params)
                }).catch(() => {});
            },
            // 保存
            save() {
                let _this = this,
                    url = api.companyCrd,
                    params = this.formValue

                if (params['id'] && params['id'] != '') {
                    params['type'] = 1
                    url = api.companyEdt
                }

                _this.handleAxiosFun(url, params)
            },
            // 账号修改
            userEdit(row) {
                let _this = this

                if (_this.$store.getters.userInfo.is_mod === 0) {
                    _this.$confirm('账户只允许修改一次，您确认要修改吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.$prompt('请输入新的账号：格式【字母开头，2到20位字符】', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            inputPattern: /^[a-z]\w{1,19}$/,
                            inputErrorMessage: '账户格式不正确'
                        }).then(({
                            value
                        }) => {
                            let params = {
                                id: row.userid,
                                username: value
                            }
                            let _sucess_callback = function() {
                                _this.$store.dispatch("LogOut").then(() => {
                                    _this.$router.push({
                                        path: "/login"
                                    });
                                });
                            }
                            _this.handleAxiosFun(api.user_account_modify, params, _sucess_callback)
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '取消输入'
                            });
                        });
                    })
                } else {
                    this.$alert('账户只允许修改一次，您已修改过！', '提示', {
                        confirmButtonText: '确定'
                    });
                }
            },
            lookDetail(row) {
                this.$set(this.formConfig[0], 'disabled', true)
                this.formValue = Object.assign({}, row)
                this.dialogFormVisible = true
                this.dialogFormTitle = '查看【' + row.name + '】单位'
            },
            // axios接口请求
            handleAxiosFun(url, params, _sucess_callback, _fail_callback) {
                let _this = this

                _this.axios.post(url, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'success'
                        });
                        if (_sucess_callback && typeof _sucess_callback === 'function') {
                            _sucess_callback()
                        } else {
                            _this.getTableList()
                            _this.handleCloseBindDialogForm()
                        }
                    } else {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                        if (_fail_callback && typeof _fail_callback === 'function') {
                            _fail_callback()
                        }
                    }
                }).catch(() => {
                    _this.$message({
                        showClose: false,
                        message: '调用失败',
                        type: 'error'
                    });
                })
            }
        }
    }
</script>

<style lang="scss">
    .avue-crud__right {
        position: relative;
    }

    .fast-search {
        position: absolute;
        right: 218px;
    }
</style>
